package data_access

import (
	"gorm.io/gorm"
)

func GetUserById(id int64) (*User, error) {
	var user User
	err := DB.First(&user, id).Error
	return &user, err
}

func GetUserByUserName(username string) (*User, error) {
	var user User
	err := DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}

func Register(username, password string) (*User, error) {
	var user User
	user.Name = username
	user.PassWord = password
	user.Type = 1
	user.FollowNum = 0
	user.FollowerNum = 0
	user.PostNum = 0
	err := DB.Create(&user).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}

func GetFollowingList(userId int64, page, size int) (users []User, total int64, err error) {
	var followRefs []FollowRef
	db := DB.Model(&FollowRef{}).Where("follower_id = ?", userId)
	db.Count(&total)
	err = db.Offset((page - 1) * size).Limit(size).Find(&followRefs).Error
	if err != nil {
		return
	}

	var userIds []int64
	for _, ref := range followRefs {
		userIds = append(userIds, ref.UpId)
	}

	err = DB.Where("id IN ?", userIds).Find(&users).Error
	return
}

func IsFollowing(userId, followerId int64) (bool, error) {
	var count int64
	err := DB.Model(&FollowRef{}).Where("up_id = ? AND follower_id = ?", userId, followerId).Count(&count).Error
	return count > 0, err
}

func FollowUser(userId, followerId int64) error {
	return DB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Create(&FollowRef{UpId: userId, FollowerId: followerId}).Error; err != nil {
			return err
		}
		if err := tx.Model(&User{}).Where("id = ?", userId).UpdateColumn("follower_num", gorm.Expr("follower_num + ?", 1)).Error; err != nil {
			return err
		}
		return tx.Model(&User{}).Where("id = ?", followerId).UpdateColumn("follow_num", gorm.Expr("follow_num + ?", 1)).Error
	})
}
